<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
class Admin extends Model
{
	protected string $table = 'admin';
	protected string $pk = 'id';
    protected array $validate = [
        ['username', 'username|unique', '账户4-20位|账户已存在', IF_MUST, AC_INSERT],
        ['nickname', 'unique', '昵称已存在', IF_MUST, AC_BOTH],
        ['password', 'required', '请输入密码', IF_MUST, AC_INSERT],
        ['password', 'password', '密码5-12位', IF_VALUE, AC_BOTH],
        ['re_password', 'confirmed:password', '确认密码不一致', IF_MUST, AC_BOTH],
        ['email', 'email', '邮箱格式错误', IF_VALUE, AC_BOTH],
        ['mobile', 'mobile', '手机号格式错误', IF_VALUE, AC_BOTH],
        ['qq', 'qq', 'QQ号格式错误', IF_VALUE, AC_BOTH],
    ];
    protected array $auto = [
        ['password', 'setPassword', 'method', IF_VALUE, AC_BOTH],
        ['status', '1', 'string', IF_MUST, AC_INSERT],
    ];
    protected array $filter = [
        ['username', IF_ISSET, AC_UPDATE],
        ['password', IF_EMPTY, AC_UPDATE],
    ];

    // 自动加密
    public function setPassword(string $password, array $data): string
    {
        return $this->getEncryptPassword($password, $data['username']);
    }

    // 密码加密
    public function getEncryptPassword(string $password, string $salt = ''): string
    {
        return md5(md5($password) . $salt);
    }

    // 获取头像
    public function getAvatarAttr(string $val, array $data): string
    {
        return !empty($val) ? trim($val, '.') : __STATIC__ . '/admin/images/avatar.png';
    }

    protected function _before_update(array &$data): void
    {
        if (session('user.id') != 1) {
            $this->db = $this->db->where('id<>1'); // 不允许修改admin账户
        }
    }

    protected function _before_delete(array $data): void
    {
        $this->db = $this->db->where('id<>1'); // 不允许删除admin账户
    }

    protected function _after_delete(array $data): void
    {
        if (!empty($data['avatar'])) {
            $avatar = ROOT_PATH . '/public' . trim($data['avatar'], '.');
            if (file_exists($avatar)) {
                unlink($avatar); // 删除头像
            }
        }
    }

    // 登录逻辑
    public function login(array $req): bool
    {
        $rule = [
            ['username', 'username', '账户4-20位'],
            ['password', 'password', '密码5-12位'],
            ['captcha', 'captcha', '验证码错误'],
        ];
        $errors = validate($rule, $req)->getError();
        if (!empty($errors)) {
            $this->errors[] = current($errors);
            return false;
        }
        $user = $this->db->field('id,group_id,username,nickname,password,work_menu,status')->where('username', $req['username'])->find();
        if (!$user) {
            $this->errors[] = '账户不存在';
            return false;
        }
        if ($user['status'] == 0 && $user['id'] != 1) {
            $this->errors[] = '账户已停用';
            return false;
        }
        if ($user['password'] != $this->getEncryptPassword($req['password'], $user['username'])) {
            $this->errors[] = '密码不正确';
            return false;
        }
        unset($user['password'], $user['status']);
        session('user', $user);
        $this->db->where('id', $user['id'])->inc('login_count')->update(['login_ip' => get_int_ip(), 'login_time' => time()]);
        return true;
    }

    // 修改密码
    public function changePassword(array $req): bool
    {
        // 演示设置
        if (config_get('cms.is_demo', true)) {
            $this->errors[] = '演示模式禁止修改密码';
            return false;
        }
        $rule = [
            ['old_pwd', 'password', '旧密码5-12位'],
            ['new_pwd', 'password', '新密码5-12位'],
            ['re_pwd', 'confirmed:new_pwd', '确认密码不一致'],
        ];
        $errors = validate($rule, $req)->getError();
        if (!empty($errors)) {
            $this->errors[] = current($errors);
            return false;
        }
        $uid = session('user.id');
        $user = $this->db->field('username,password')->where('id', $uid)->find();
        if ($user['password'] != $this->getEncryptPassword($req['old_pwd'], $user['username'])) {
            $this->errors[] = '旧密码错误';
            return false;
        }
        $newPassword = $this->getEncryptPassword($req['new_pwd'], $user['username']);
        $result = $this->db->where('id', $uid)->setField('password', $newPassword);
        if (!$result) {
            $this->errors[] = '修改失败';
        }
        return (bool)$result;
    }
}